package com.hwd.gmall.order.controller;

import com.hwd.gmall.common.constant.OrderConst;
import com.hwd.gmall.common.result.Result;
import com.hwd.gmall.common.util.MyThreadLocal;
import com.hwd.gmall.model.enums.OrderStatus;
import com.hwd.gmall.model.order.OrderInfo;
import com.hwd.gmall.order.service.OrderService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 订单模块的控制层
 *
 * @author 黄伟东/Victor
 * @date 2022/5/7 22:42
 */
@RestController
@RequestMapping(value = "/api/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 新增订单
     *
     * @param orderInfo 订单信息
     * @return com.hwd.gmall.common.result.Result<java.lang.Void>
     */
    @PostMapping(value = "/addOrder")
    public Result<Void> addOrder(@RequestBody OrderInfo orderInfo) {
        orderService.addOrder(orderInfo);
        return Result.ok();
    }

    /**
     * 主动取消订单
     *
     * @param orderId 订单id
     * @return com.hwd.gmall.common.result.Result<java.lang.Void>
     */
    @PostMapping(value = "/cancelOrder")
    public Result<Void> cancelOrder(Long orderId) {
        // 防止并发重复取消订单
        Long increment = redisTemplate
                .opsForValue().increment(OrderConst.USER_ORDER_CANCEL_COUNT + MyThreadLocal.get(), 1);
        try {
            if (increment != null && increment == 1) {
                orderService.cancelOrder(orderId, OrderStatus.CANCEL.getComment());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            redisTemplate.delete(OrderConst.USER_ORDER_CANCEL_COUNT + MyThreadLocal.get());
        }
        return Result.ok();
    }
}
